package zhaoq_hero.superapp;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.ColorFilter;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;

import zhaoq_hero.superapp.fragments.HistoryFragment;
import zhaoq_hero.superapp.interfaces.MyCallBack;
import zhaoq_hero.superapp.interfaces.MyCallBack1;
import zhaoq_hero.superapp.providers.DataContract;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, MyCallBack1, MyCallBack {

    private Button ok;

    private WebView webView;
    private Button history;
    private Button back;
    private Button forward;
    private EditText http;
    private ProgressBar progressBar;

    private String currentUrl;

    private String currentTitle;

    private long lastClick;

    //控制返回的次数   如果小于2，那么说明是第一次进入浏览器  不做存储
    private int currentCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        history = (Button) findViewById(R.id.history);
        history = (Button) findViewById(R.id.history);
        back = (Button) findViewById(R.id.back);
        forward = (Button) findViewById(R.id.forward);
        webView = (WebView) findViewById(R.id.webview);
        http = (EditText) findViewById(R.id.http);
        ok = (Button) findViewById(R.id.ok);
        progressBar = (ProgressBar) findViewById(R.id.progress);

        ok.setOnClickListener(this);
        history.setOnClickListener(this);
        back.setOnClickListener(this);
        forward.setOnClickListener(this);


        webView.setWebViewClient(new MyWebViewClient(this));
        webView.setWebChromeClient(new MyChromClient(this));
        webView.loadUrl("http://www.baidu.com");

    }


    //添加记录  并刷新

//    public void btnAddhistory(
//            View view){
//
//        ContentResolver resolver = getContentResolver();
//
//        ContentValues values = new ContentValues();
//
//        values.put(DataContract.History.URL, "http://www.baidu.com");
//
//        /**
//         * 添加记录  并返回添加记录的访问 Uri
//         */
//        Uri rowUri = resolver.insert(DataContract.History.CONTENT_URI,
//                values
//        );
//
//        if (rowUri != null) {
//
//            Toast.makeText(this,rowUri.toString(),Toast.LENGTH_LONG).show();
//
//            FragmentManager fragmentManager = getSupportFragmentManager();
//
//            Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_history);
//
//            if (fragment != null) {
//                if (fragment instanceof HistoryFragment){
//
//                    HistoryFragment historyFragment = (HistoryFragment) fragment;
//
//                    historyFragment.refreshHistory();
//                }
//            }
//        }
//    }
//    /**
//     * 将内容   切换为横屏  显示
//     * @param view
//     */
//    public void btnswitchLandScreen(View view){
//        //切换屏幕
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//
//    }

    /**
     * 当屏幕变化的情况：
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        Log.i("info", newConfig.orientation + "");

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            //横屏情况：


        }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            //竖屏的情况：


        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.ok:

                String url = http.getText().toString();

                if (url != null) {
                        if (url.startsWith("www")) {
                            url = "http://" + url;
                            http.setText(url);
                        }

                currentUrl = url;

                String currentTime = getTimeString();
                    // TODO 保存数据到数据库
                    ContentResolver contentResolver = getContentResolver();
                    ContentValues values = new ContentValues();
                    values.put(DataContract.History.URL, url);
                    values.put(DataContract.History.TIME, currentTime);

                    Uri rowUri = contentResolver.insert(DataContract.History.CONTENT_URI, values);
                    if (rowUri != null) {
                        Log.d("debug111", "uri = " + rowUri);
                    }

                    webView.loadUrl(url);

                } else {
                    Toast.makeText(this, "您输入的网址有误，请重新输入", Toast.LENGTH_SHORT).show();
                }

                break;

            //前进：
            case R.id.forward:

                if (webView.canGoForward())
                    webView.goForward();

                break;

            //后退
            case R.id.back:

                if (webView.canGoBack())
                    webView.goBack();

                break;

            //查看历史
            case R.id.history:

                Intent intent = new Intent(this, HistoryActivity.class);
                intent.putExtra("type","history");
                startActivityForResult(intent, 0);

                break;

        }
    }

    //接受回传数据：
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {
            if (data.getStringExtra("url") != null) {
                String url = data.getStringExtra("url");
                try {
                    http.setText(URLEncoder.encode(url, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                webView.loadUrl(url);
            }
        }
    }


    //获取当前时间：
    private String getTimeString() {
        Calendar c = Calendar.getInstance();

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        int minute = c.get(Calendar.MINUTE);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        return String.format("%d年%d月%d日:%d时-%d分",
                year, month, day, hour, minute);
    }


    //当点击  返回键时：
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            long currentClick = System.currentTimeMillis();

            if (currentClick - lastClick < 3000) {
                finish();
            } else {
                lastClick = currentClick;
                Toast.makeText(this, "再次点击退出程序", Toast.LENGTH_SHORT).show();
            }
        }
        return true;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.bookmenu,menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_book:
                // TODO 添加书签
                if(progressBar.getProgress()==100){
                    ContentResolver resolver = getContentResolver();
                    ContentValues values = new ContentValues();
                    String url = http.getText().toString();
                    values.put(DataContract.BookMark.URL, url);
                    values.put(DataContract.BookMark.TITLE,currentTitle);
                    Cursor addCursor = resolver.query(
                            DataContract.BookMark.BOOK_URI,
                            null,
                            DataContract.BookMark.URL+" ='"+ url +"'",
                            null,
                            null
                    );
                    if(addCursor==null||addCursor.getCount()==0){
                        resolver.insert(DataContract.BookMark.BOOK_URI,
                                values);
                    }else{
                        Toast.makeText(this,"这个网址已经是书签了",Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.see_book:
                Intent intent = new Intent(this,HistoryActivity.class);
                intent.putExtra("type","book");
                startActivityForResult(intent,0);
                break;
        }
        return true;
    }

    //回调url，将获取到的数据url的地址返回：
    @Override
    public void sendUrl(String url) {
        if (currentCount >= 2) {
            if (url != null) {
                if (!url.equals(currentUrl)) {
                    ContentResolver resolver = getContentResolver();

                    //执行查询
                    Cursor cursor = resolver.query(DataContract.History.CONTENT_URI,
                            null,
                            DataContract.History.TITLE + "='" + currentTitle + "'",
                            null,
                            null);

                    Log.d("debug11", "长度为:" + cursor.getCount());

                    if (cursor.getCount() > 0) {
                        cursor.moveToLast();
                        if (cursor.getString(1).equals("")) {
                            ContentValues values = new ContentValues();
                            values.put(DataContract.History.URL, url);
                            resolver.update(DataContract.History.CONTENT_URI,
                                    values,
                                    DataContract.History.TITLE + "='" + currentTitle + "'",
                                    null);
                            http.setText(url);
                        }
                    }

                }
            }
        }else
            currentCount++;
    }

    //进度回调  设置当前进度：：
    @Override
    public void onProgressChanged(int newProgress) {

        progressBar.setProgress(newProgress);

    }

    //标题回调：
    @Override
    public void onReceivedTitle(String title) {
        setTitle(title);
        //  TODO 查询数据库 插入标题字段
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(DataContract.History.CONTENT_URI,
                null,
                DataContract.History.URL + "='" + http.getText().toString() + "'",
                null,
                null);

        ContentValues values = new ContentValues();
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToLast();
            String dbTitle = cursor.getString(2);
            if (dbTitle != null) {//dbTitle 不为空说明是一个新的网址
                Log.d("debug111", "新的网址  " + title);
                values.put(DataContract.History.URL, "");
                values.put(DataContract.History.TIME, getTimeString());
                values.put(DataContract.History.TITLE, title);
                currentTitle = title;
                Uri rowUri = resolver.insert(DataContract.History.CONTENT_URI, values);
            } else {
            //旧的网址 将title存进去
                int id = cursor.getInt(cursor.getColumnIndex(DataContract.History._ID));
                values.put(DataContract.History.TITLE, title);
                resolver.update(DataContract.History.CONTENT_URI,
                        values,
                        DataContract.History._ID + "=" + id,
                        null);
            }
        } else if(currentCount>=2){
            Log.d("debug111", "新的网址1  " + title);
            values.put(DataContract.History.URL, "");
            values.put(DataContract.History.TIME, getTimeString());
            values.put(DataContract.History.TITLE, title);
            currentTitle = title;
            resolver.insert(DataContract.History.CONTENT_URI, values);
        }
        setTitle(currentTitle);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
